package com.chen.authority.common.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.CharsetUtil;
import com.chen.authority.entity.ExcelVerifyInfoEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;

/**
 * excel 工具类
 *
 * @author chengy
 * @date 2022/11/04
 */
public class ExcelUtil {

    /**
     * 通用导入方法
     *
     * @param file      文件
     * @param pojoClass 实体类
     * @return 实体集合
     */
    public static <T extends ExcelVerifyInfoEntity> List<T> importExcel(MultipartFile file, Class<T> pojoClass) {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1); //去掉标题行
        importParams.setNeedVerify(true);
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ExcelImportResult<T> eir = ExcelImportUtil.importExcelMore(inputStream, pojoClass, importParams);
            verifyData(eir);
            return eir.getList();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            IoUtil.close(inputStream);
        }
    }

    /**
     * 通用导出方法
     *
     * @param response  响应
     * @param filename  文件名
     * @param pojoClass 实体类
     * @param data      实体数据
     */
    public static void exportExcel(HttpServletResponse response, String filename, Class<?> pojoClass, Collection<?> data) {
        ExportParams exportParams = new ExportParams(filename, filename, ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, data);
        ServletOutputStream outputStream = null;
        try {
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setHeader("content-type", "application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(outputStream);
        }
    }

    /**
     * 处理校验信息（拼接完整校验信息）
     *
     * @param excelImportResult excel导入结果
     */
    private static <T extends ExcelVerifyInfoEntity> void verifyData(ExcelImportResult<T> excelImportResult) {
        if (excelImportResult.isVerifyFail()) {
            StringBuilder fullErrorMessage = new StringBuilder();
            for (T fail : excelImportResult.getFailList()) {
                fullErrorMessage.append("第")
                        .append(fail.getRowNum() + 1)
                        .append("行，")
                        .append(fail.getErrorMsg())
                        .append(StrPool.LF);
            }
            throw new RuntimeException(fullErrorMessage.toString());
        }
    }

}